#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

static const int N=2;

// child
void Writer(int wfd)
{
    std::string s = "Hello, I am child";
    pid_t self = getpid();
    int number = 0;
    char wbuffer[1024];
    while (true)
    {
        // 构建发送字符串
        wbuffer[0] = 0;
        snprintf(wbuffer, sizeof(wbuffer), "%s-%d-%d", s.c_str(), self, number++);
        // 发送给父进程
        write(wfd, wbuffer, strlen(wbuffer));
        sleep(1);
    }
}

// father
void Reader(int rfd)
{
    char rbuffer[1024];
    while (true)
    {
        rbuffer[0] = 0;
        ssize_t n = read(rfd, rbuffer, sizeof(rbuffer));
        if(n > 0)
        {
            rbuffer[n] = 0;
            std::cout << "father get a message from child: [" << getpid() << "]@ " << rbuffer << std::endl;
        }
        else if(n == 0)
        {
            std::cout << "father read file done" << std::endl;
            break;
        }
        else
            break;
    }
    
}

int main()
{
    int pipefd[N] = {0};
    int n = pipe(pipefd);
    if(n < 0)   return errno;
    
    // std::cout << "pipefd[0]: " << pipefd[0] << ", pipefd[1]: " << pipefd[1] << std::endl;

    // 让child 写，father 读
    pid_t id = fork();
    if(id < 0)
    {
        perror("fork");
        return errno;
    }
    else if(id == 0)
    {
        // child
        close(pipefd[0]);       // 子进程关闭读端

        Writer(pipefd[1]);      // 子进程的写操作

        close(pipefd[1]);
        exit(0);
    }
    // father
    close(pipefd[1]);       // 父进程关闭写端

    Reader(pipefd[0]);  // 父进程的读操作

    pid_t rid = waitpid(id, nullptr, 0);    // 阻塞等待
    if(rid < 0)
    {
        perror("waitpid");
        return errno;
    }
    close(pipefd[0]);   // 通信结束，关闭读端

    return 0;
}
